<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="新增应用"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { createConnection } from '@/api/connection'
  import { partnerTypeEnum } from '@/enums/partner';

  const emit = defineEmits(['success', 'register']);

  const formSchema: FormSchema[] = [
    {
      field: 'app_register_api',
      label: '注册API',
      component: 'Input',
      required: true,
    },
    {
      field: 'time',
      component: 'RangePicker',
      label: '有效日期',
      required: true,
    },
  ];

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      [values.start_time, values.end_time] = values.time;
      delete values.time;
      values.type = partnerTypeEnum.APP;
      setDrawerProps({ confirmLoading: true });
      await createConnection(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>